#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int castle[50][50];
vector<pair<int, int>> color; // 房间id,房间个数
int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
int color_id = 0;
int color_num = 0;
void bfs(int m, int n)
{
    queue<int, int> pre_node;
    for (size_t i = 0; i < m; i++)
    { // 寻找起点
        for (size_t j = 0; j < n; j++)
        {
            if ((castle[i][j] & 1 == 1) || (castle[i][j] & 2 == 1) || (castle[i][j] & 4 == 1) || (castle[i][j] & 8 == 1))
            {
                pre_node.push(make_pair(i, j));
                break;
            }
        }
    }
    int x, y;
    color_id += 1;
    color_num = 0;
    while (!pre_node.empty())
    {
        for (size_t i = 0; i < 4; i++)
        {
            x = pre_node.front().first;
            y = pre_node.front().second;
            x = x + dir[i][0];
            y = y + dir[i][1];
            if (castle[x][y] & 1 == 1) // 向左走
            {
                pre_node.push(make_pair(x, y));
                break;
            }
        }
        pre_node.pop();
    }
}
int main()
{
    int m, n;
    memset(castle, 0, sizeof(castle)); // castle进行初始化
    for (size_t i = 0; i < m; i++)
    {
        for (size_t j = 0; j < n; j++)
        {
            cin >> castle[i][j];
        }
    }
    bfs(m, n);
}